package com.jdb.settings.controller;

import com.guns21.result.domain.Result;
import com.guns21.support.controller.BaseController;
import com.jdb.settings.api.SettingDTO;
import com.jdb.settings.controller.assembler.SettingAssembler;
import com.jdb.settings.privoder.service.SettingsCommandService;
import com.jdb.settings.privoder.service.SettingsQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;

/**
 * @author jliu
 */
@RestController
@RequestMapping("/api/settings/v1")
public class SettingsController extends BaseController {
    @Autowired
    private SettingsQueryService settingsQueryService;
    @Autowired
    private SettingsCommandService settingsCommandService;

    @GetMapping("/key/{key}")
    public Result<SettingDTO> get(@PathVariable String key) {
        return settingsQueryService.get(key);
    }

    @PostMapping("/save")
    public Result<SettingDTO> save(@Valid @RequestBody SettingDTO settingDTO) {
        Result<SettingDTO> settingDTOResult = settingsQueryService.get(settingDTO.getKey());
        if (settingDTOResult.getSuccess()) {
            SettingDTO data = settingDTOResult.getData();
            if (Objects.nonNull(data)) {
                settingDTO.setId(data.getId());
            }
        }
        settingsCommandService.save(SettingAssembler.fromDTO(settingDTO));
        return Result.success();
    }

}
